//
//  SNSleepDetailView.m
//  project
//
//  Created by 黄建华 on 2017/12/6.
//  Copyright © 2017年 黄建华. All rights reserved.
//

#import "SNSleepDetailView.h"
#define CHARTHEIGHT       150.0
#define ACTIONTIME        0.5

@implementation SNSleepDetailView

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor     = [UIColor whiteColor];
    }
    return self;
}

- (void)updateView
{
    if (_chartView) {
        [_chartView removeFromSuperview];
        _chartView = nil;
        
    }
    if (_topView) {
        [_topView removeFromSuperview];
        _topView = nil;
    }
    _topView                 = [[UIView alloc] init];
    _topView.frame           = SNFRAME(0, 0, self.width, self.height);
    _topView.backgroundColor = [UIColor whiteColor];
    [self addSubview:_topView];
    
    _chartView       = [[UIView alloc] init];
    _chartView.frame = SNFRAME(0, 30, self.width, CHARTHEIGHT);
    [_topView addSubview:_chartView];
    
    [self createChartView];
}

- (void)createChartView {
    // 获取睡眠数据
    SleepModel *model = [SleepModel getSleepModelFromDBWith:SN_PublicClass.selectDate];
    //    NSLog(@" 睡眠>>>>>睡眠总时长%d 有效时长>>>%d",model.durations,model.effDuration);
    NSString *timeInBed = [NSString stringWithFormat:@"%d%@ %02d%@", model.durations/60, SN_Text(@"h"), model.durations%60, SN_Text(@"mins")];
    
    NSString *timeAsleep = [NSString stringWithFormat:@"%d%@ %02d%@", model.effDuration/60, SN_Text(@"h"), model.effDuration%60, SN_Text(@"mins")];
    
    NSString *qualityString = SN_Text(model.compareQuality);
    
    if (model.durations == 0) {
        qualityString = SN_Text(@"暂无数据");
    }
    
    NSArray *array      = [NSArray arrayWithObjects:SNSLEEPCOLORDEEP, SNSLEEPCOLORLIGHT, SNSLEEPCOLORSOBER, nil];
    NSArray *labelArray = [NSArray arrayWithObjects:SN_Text(@"深睡"), SN_Text(@"浅睡"), SN_Text(@"清醒"), nil];
    
    NSArray *valueArray = [NSArray arrayWithObjects:timeInBed, timeAsleep, qualityString, nil];
    NSArray *unitArray  = [NSArray arrayWithObjects:SN_Text(@"总睡眠时长"), SN_Text(@"有效睡眠时长"), SN_Text(@"睡眠质量"), nil];
    
    for (int i = 0; i < 3; i++) {
        //图例 方块
        UIView *view = [[UIView alloc] init];
        view.frame           = SNFRAME(0, 6, 10, 10);
        view.backgroundColor = array[i];
        [self addSubview:view];
        if (i == 0) {
            view.center = CGPointMake(HHHWIDTH/4 -20, 10);
        }
        if (i == 1) {
            view.center = CGPointMake(self.center.x - 20, 10);
        }
        if (i == 2) {
            view.center = CGPointMake(HHHWIDTH/4 *3 - 20, 10);
        }
        //图例 文字
        UILabel *label = [[UILabel alloc] init];
        label.frame         = SNFRAME(0, 0, 77, 15);
        label.center        = CGPointMake(view.center.x + 12 + label.width /2.0, view.center.y);
        label.textAlignment = NSTextAlignmentLeft;
        label.font          = SNSFONT(10.0);
        label.adjustsFontSizeToFitWidth = YES;
        label.text          = labelArray[i];
        [self addSubview:label];
        
        UILabel *labelValue = [[UILabel alloc] init];
        labelValue.frame         = SNFRAME(0, 0, 90, 15);
        labelValue.center        = CGPointMake(i*HHHWIDTH/3 +HHHWIDTH/6, view.center.y + CHARTHEIGHT + 52);
        labelValue.textAlignment = NSTextAlignmentCenter;
        labelValue.font          = SNFONT(14.5);
        labelValue.text          = valueArray[i];
        [labelValue setAdjustsFontSizeToFitWidth:YES];
        [self addSubview:labelValue];
        
        if (i != 2) {
            [labelValue setAttributedText:[SN_PublicClass label1With:labelValue.text withFontsize:10.0 withChangeText1:SN_Text(@"h") withChangeText2:SN_Text(@"mins")]];
        }
        
        UILabel *unitValue = [[UILabel alloc] init];
        unitValue.frame         = SNFRAME(0, 0, 100, 15);
        unitValue.center        = CGPointMake(i*HHHWIDTH/3 +HHHWIDTH/6, labelValue.center.y + 18);
        unitValue.textAlignment = NSTextAlignmentCenter;
        unitValue.font          = SNFONT(12.0);
        unitValue.textColor     = SNCOLORGRAY;
        unitValue.text          = unitArray[i];
        [self addSubview:unitValue];
    }
    
    CGFloat originX = 10;
    //  图表XY线
    UIView *lineView1 = [[UIView alloc] init];
    lineView1.frame           = SNFRAME(originX, 0, 1, _chartView.height);
    lineView1.backgroundColor = SNCOLORGRAYLINE;
    [_chartView addSubview:lineView1];
    
    UIView *lineView2 = [[UIView alloc] init];
    lineView2.frame           = SNFRAME(originX, _chartView.height - 1, _chartView.width - 2*originX, 1);
    lineView2.backgroundColor = SNCOLORGRAYLINE;
    [_chartView addSubview:lineView2];
    
    CGFloat MaxwidthL  = self.width - 2 *originX;
    CGFloat MaxheightL = CHARTHEIGHT;
    
    CGFloat speceL   = 10;
    CGFloat originX_ = 0.0;
    // 如果有多段间距是 10
    if (model.sleepsubArray.count > 1) {
        MaxwidthL = MaxwidthL - (model.sleepsubArray.count -1)* speceL;
    }
    
    NSArray *sortedArray = [model.sleepsubArray sortedArrayUsingComparator:^NSComparisonResult (id _Nonnull obj1, id _Nonnull obj2) {
        SleepSubModel *suSleepModel1 = (SleepSubModel *)obj1;
        SleepSubModel *suSleepModel2 = (SleepSubModel *)obj2;
        return [suSleepModel1.subendTime compare:suSleepModel2.subendTime]; //升序
    }];
    //    NSLog(@"sortedArray>>>>>%@",sortedArray);
    
    NSMutableArray *arrA = [NSMutableArray arrayWithArray:sortedArray];
    for (int i = 0; i < arrA.count; i++) {
        SleepSubModel *submodel = [arrA objectAtIndex:i];
        CGFloat       width     = 1.0 * submodel.subtotalduration / model.durations * MaxwidthL;
        if (i > 0) {
            UIView *lineViewSpace = [[UIView alloc] init];
            lineViewSpace.frame           = SNFRAME(10 + 5 +originX_, -10, 1, _chartView.height + 10);
            lineViewSpace.backgroundColor = SNCOLORGRAYLINE;
            [_chartView addSubview:lineViewSpace];
        }
        CGRect lastFrame ;
        for (int k = 0; k < submodel.subsleepData.count; k++) {
            if (k == 0) {
                UILabel *beginLabel = [[UILabel alloc] init];
                beginLabel.textAlignment = NSTextAlignmentLeft;
                //入睡时间 从后面往前推算 //临时解决硬件掉电部分问题
                /*
                NSString *etime = [submodel.subendTime componentsSeparatedByString:@" "][1];
                etime = [NSString subString:etime withToIndex:5];
                NSArray   *endTimeA = [etime componentsSeparatedByString:@":"];
                NSInteger endtimeS  = [[endTimeA firstObject] intValue] *60 + [[endTimeA lastObject]intValue];
                NSInteger begin     = 0;
                NSInteger sleepT    = submodel.subtotalduration;
                if (endtimeS - sleepT >= 0) {
                    begin = endtimeS - sleepT;
                } else {
                    begin = 24*60 - (sleepT - endtimeS);
                }
                
                NSString *time = [NSString stringWithFormat:@"%02ld:%02ld", begin/60, begin%60];
                 */
                NSString *time = [submodel.substartTime componentsSeparatedByString:@" "][1];
                time                 = [NSString subString:time withToIndex:5];
                beginLabel.text      = time;
                beginLabel.textColor = SNCOLORBLACK;
                [_chartView addSubview:beginLabel];
                if (arrA.count == 1) {
                    beginLabel.font = SNFONTMIN(8.0);
                } else {
                    beginLabel.font = SNFONTMIN(7.0);
                }
                if (i == 0) {
                    beginLabel.frame = SNFRAME(originX_ +i*speceL + 8*i +4, _chartView.height, 40, 15);
                } else {
                    beginLabel.frame = SNFRAME(originX_ +i*speceL + 8*i , _chartView.height, 40, 15);
                }
                beginLabel.adjustsFontSizeToFitWidth = YES;
                
                if (arrA.count >1) {
                   BOOL isMutul =CGRectIntersectsRect(beginLabel.frame,lastFrame);
                    if (isMutul) {
                        beginLabel.hidden = YES;
                    }
                }
            }
            int    number        = [submodel.subsleepData[k] intValue];
            int    sleepStatus   = (UInt8)(number >> 14);
            int    sleepTime     = (UInt16)number & 0x3FFF;
            UIView *ColumnarView = [[UIView alloc] init];
            // 时间占总时间计算宽度(开始位置)
            CGFloat viewWidth = 1.0* sleepTime / submodel.subtotalduration *width;
            // 从左到右
            CGFloat originY = 0.0;
            // 0浅睡 01深睡 02醒着
            if (sleepStatus == 0) {
                originY                      = CHARTHEIGHT/3;
                ColumnarView.backgroundColor = SNSLEEPCOLORLIGHT;
            } else if (sleepStatus == 1) {
                originY                      = 0.0;
                ColumnarView.backgroundColor = SNSLEEPCOLORDEEP;
            } else if (sleepStatus == 2) {
                originY                      = CHARTHEIGHT/3 *2;
                ColumnarView.backgroundColor = SNSLEEPCOLORSOBER;
            }
            CGFloat ColumnarViewOX = originX +i *10.0 +originX_;
            ColumnarView.frame = SNFRAME(ColumnarViewOX, originY, viewWidth, CHARTHEIGHT/3.0);
            // 下一段的开始位置等于上一段之和
            [_chartView addSubview:ColumnarView];
            
            originX_ += viewWidth;
            // 中间的连接线逻辑 以及绘图
            if (k > 0) {
                int lastnumber      = [submodel.subsleepData[k -1] intValue];
                int lastsleepStatus = (UInt8)(lastnumber >> 14);
                if ((lastsleepStatus == 1 && sleepStatus == 2) || (lastsleepStatus == 2 && sleepStatus == 1)) {
                    UIView *connectinLine = [[UIView alloc] init];
                    connectinLine.frame           = SNFRAME(ColumnarView.origin.x - 0.5, CHARTHEIGHT/3, 1, CHARTHEIGHT/3);
                    connectinLine.backgroundColor = SNCOLORGRAYLINE;
                    [_chartView addSubview:connectinLine];
                }
            }
            //睡眠
            if (k == submodel.subsleepData.count - 1) {
                UILabel *beginLabel = [[UILabel alloc] init];
                beginLabel.textAlignment = NSTextAlignmentLeft;
                if (arrA.count == 1) {
                    beginLabel.font = SNFONTMIN(8.0);
                } else {
                    beginLabel.font = SNFONTMIN(7.0);
                }
                if (i == 0) {
                    beginLabel.frame = SNFRAME(originX_ +i*speceL - 8, _chartView.height, 40, 15);
                } else {
                    beginLabel.frame = SNFRAME(originX_ +i*speceL - 5, _chartView.height, 40, 15);
                }
                
                if (arrA.count >1) {
                    lastFrame = beginLabel.frame;
                }
                
                beginLabel.adjustsFontSizeToFitWidth = YES;
                
                NSString *time = [submodel.subendTime componentsSeparatedByString:@" "][1];
                time                 = [NSString subString:time withToIndex:5];
                beginLabel.text      = time;
                beginLabel.textColor = SNCOLORBLACK;
                [_chartView addSubview:beginLabel];
            }
        }
    }
    
    SNShadowView *lineView_1 = [[SNShadowView alloc] init];
    [lineView_1 showWithType:1];
    lineView_1.frame = SNFRAME(0, _chartView.origin.y + _chartView.height + 90 - FitSimpleSize(20, 20, 0, 0, 0), HHHWIDTH, 3);
    [self addSubview:lineView_1];
    
    UIImageView *sleepImg = [[UIImageView alloc] init];
    sleepImg.frame = SNFRAME(10, _chartView.origin.y + _chartView.height + 90 - FitSimpleSize(20, 20, -10, -10, -10), 60, 60);
    sleepImg.image = [UIImage imageNamed:@"睡眠"];
    [self addSubview:sleepImg];
    
    UILabel *sleepTypeLabel = [[UILabel alloc] init];
    sleepTypeLabel.textAlignment = NSTextAlignmentLeft;
    sleepTypeLabel.frame         = SNFRAME(sleepImg.center.x + 45, sleepImg.center.y - 8, 200, 20);
    sleepTypeLabel.textColor     = SNCOLORBLACK;
    sleepTypeLabel.text          = SN_Text(@"睡眠详情");
    sleepTypeLabel.font          = SNFONT(17.0);
    [self addSubview:sleepTypeLabel];

    UIButton *detailBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    detailBtn.frame = SNFRAME(sleepTypeLabel.right - 60, sleepTypeLabel.top -5, 100, 30);
    [detailBtn setTitleNormal:HHH_Text(@"关于睡眠准确度")];
    detailBtn.titleLabel.font = SNFONTMIN(12);
    [detailBtn setTitleColorNormal:SNCOLORGRAY];
    [detailBtn addTouchUpTarget:self action:@selector(showSleepView)];
    [self addSubview:detailBtn];
    
    SNShadowView *lineView_2 = [[SNShadowView alloc] init];
    [lineView_2 showWithType:1];
    lineView_2.frame = SNFRAME(0, _chartView.origin.y + _chartView.height + 150 - FitSimpleSize(20, 20, -15, -15, -15), HHHWIDTH, 3);
    [self addSubview:lineView_2];
    
    for (int i = 0; i < 3; i++) {
        //睡眠类型标签
        UILabel *sleepTypeLabel = [[UILabel alloc] init];
        sleepTypeLabel.textAlignment = NSTextAlignmentLeft;
        sleepTypeLabel.frame         = SNFRAME(10, lineView_2.center.y + 40 + i * FitSimpleSize(33, 33, 45, 50, 55) +  FitSimpleSize(0, 0, 10, 15, 20) - FitSimpleSize(10, 10, 0, 0, 0), 75, 20);
        sleepTypeLabel.textColor     = SNCOLORBLACK;
        sleepTypeLabel.adjustsFontSizeToFitWidth = YES;
        sleepTypeLabel.text          = labelArray [i];
        sleepTypeLabel.font          = SNFONT(14.0);
        [self addSubview:sleepTypeLabel];

        HWProgressView *progressView = [[HWProgressView alloc] initWithFrame:SNFRAME(8+sleepTypeLabel.center.x + sleepTypeLabel.width/2 -8, sleepTypeLabel.center.y - 15/2+2, HHHWIDTH - 85 - 88, 12)];
        [self addSubview:progressView];
        
        // 百分比标签
        UILabel *sleepCompareLabel = [[UILabel alloc] init];
        sleepCompareLabel.textAlignment = NSTextAlignmentLeft;
        sleepCompareLabel.frame         = SNFRAME(HHHWIDTH - 88 +5, sleepTypeLabel.center.y - 8, 40, 20);
        sleepCompareLabel.textColor     = SNCOLORBLACK;
        sleepCompareLabel.font          = SNFONT(11.0);
        [self addSubview:sleepCompareLabel];
        
        // 百分比标签
        UILabel *sleepTimeLabel = [[UILabel alloc] init];
        sleepTimeLabel.textAlignment = NSTextAlignmentRight;
        sleepTimeLabel.frame         = SNFRAME(HHHWIDTH - 55+5, sleepTypeLabel.center.y - 10, 50, 20);
        sleepTimeLabel.textColor     = SNCOLORBLACK;
        sleepTimeLabel.font          = SNFONT(10.0);
        sleepTimeLabel.text          = @"";
        [self addSubview:sleepTimeLabel];
        
        CGFloat progressWitdh = 0.0;
        
        if (i == 0) {
            progressWitdh          = model.compareDeep/100.0;
            progressView.tView.backgroundColor = SNSLEEPCOLORDEEP;
            sleepCompareLabel.text = [NSString stringWithFormat:@"%.1f%%", model.compareDeep];
            if (model.durations > 0) {
                sleepTimeLabel.text = [NSString stringWithFormat:@"%d %@", model.deeps, SN_Text(@"min")];
            }
        } else if (i == 1) {
            progressWitdh          = model.compareLight/100.0;
            progressView.tView.backgroundColor = SNSLEEPCOLORLIGHT;
            sleepCompareLabel.text = [NSString stringWithFormat:@"%.1f%%", model.compareLight];
            if (model.durations > 0) {
                sleepTimeLabel.text = [NSString stringWithFormat:@"%d %@", model.lights, SN_Text(@"min")];
            }
        } else if (i == 2) {
            progressWitdh          = model.compareSober/100.0;
            progressView.tView.backgroundColor = SNSLEEPCOLORSOBER;
            sleepCompareLabel.text = [NSString stringWithFormat:@"%.1f%%", model.compareSober];
            if (model.durations > 0) {
                sleepTimeLabel.text = [NSString stringWithFormat:@"%d %@", model.sobers, SN_Text(@"min")];
            }
        }
        [UIView animateWithDuration:ACTIONTIME animations:^{
            progressView.progress = progressWitdh;
        }];
    }
}

- (void)showSleepView
{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"showSleepInfo" object:nil];
}

@end

